<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">日志系统</div>
        </div>
        <div class="header-right">
          <el-button
            link
            type="primary"
            class="addRiBao"
            @click="handleAddLog"
            v-if="user.roleId == '4'"
            >发布日志</el-button
          >
        </div>
      </div>
    </div>
    <div class="class-content">
      <el-table :data="tableData" style="width: 100%" @row-click="handleRowClick">
        <el-table-column prop="userName" label="姓名" align="center" />
        <el-table-column prop="sex" label="性别" align="center" />
        <el-table-column prop="className" label="班级" align="center" />
        <el-table-column prop="time" label="时间" align="center" />
        <el-table-column prop="content" label="内容" align="center" />
      </el-table>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentPageChange"
        />
        <div> 
            每页
            <el-input-number
              v-model="pageSize"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange"
            />条
        </div>
      </div>
    </div>

    <!-- 展示日志模态框 -->
    <el-drawer  v-model="dialogVisible" title="日志详情信息" size="700" :show-close="false" style="background-color:#F0F8FF;height:100%">
      <div class="richang">
        <div class="name">
          <span class="name1">姓 名：</span>
          <span class="name2">{{ selectedRow.userName }}</span>
        </div>
        <div class="name">
          <span class="name1">性 别：</span>
          <span class="name2">{{ selectedRow.sex }}</span>
        </div>
        <div class="name">
          <span class="name1">班 级：</span>
          <span class="name2">{{ selectedRow.className }}</span>
        </div>
        <div class="date">
          <span class="date1">日 期：</span>
          <span class="date2">{{ selectedRow.time }}</span>
        </div>
        <div class="content">
          <span class="content1">内 容：</span>
          <span class="content2" v-html="selectedRow.content1"></span>
        </div>
        <div class="content">
          <span class="content1">回 复：</span>
          <span class="content2" v-html="selectedRow.answer"></span>
        </div>
       
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false" class="confirm">关闭</el-button>
      </template>
    </el-drawer >

    <!-- 发布日志 -->
    <el-drawer v-model="dialogVisibleLog" title="发布日志" size="700" :show-close="false" style="background-color:#F0F8FF">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" disabled />
          </el-form-item>
          <el-form-item label="时间" prop="date">
            <el-date-picker
              v-model="formData.date"
              type="date"
              placeholder="请选时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="职能" prop="identity">
            <!-- 下拉框 -->
            <el-select
              v-model="formData.identity"
              placeholder="请选择职能"
              style="width: 200px"
              disabled
            >
              <el-option
                v-for="item in identityList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="班级" prop="class">
            <el-input v-model="formData.class" disabled />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="性别" prop="sex">
            <!-- 下拉框 -->
            <el-select
              v-model="formData.sex"
              placeholder="请选择性别"
              style="width: 200px"
              disabled
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="内容" prop="content">
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              >
              </Toolbar>
              <Editor
                style="height: 280px; width: 558px; overflow-y: auto"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisibleLog = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-drawer>
  </div>
</template>
  
<script setup>
import {onBeforeUnmount,shallowRef, ref, onMounted } from 'vue'
import { getLog, getLogList, getLogMenu, addLog } from '../api/Log'
import { ElMessageBox ,ElMessage} from 'element-plus'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

//本地存储
const user = JSON.parse(localStorage.getItem('user'))

// 表格数据
const tableData = ref([])
// 分页相关数据
const currentPage = ref(1) // 当前页码
const pageSize = ref(7) // 每页显示的数量
const total = ref(0) // 总记录数

// 定义模态框显示状态
const dialogVisible = ref(false)
// 定义选中的行数据
const selectedRow = ref({})
// 身份标识列表
const identityList = ref([])


const mode = 'default' // 编辑器模式，'simple' 或 'default'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref()
const toolbarConfig = {
  excludeKeys: [
    'uploadImage', // 移除图片上传
    'insertImage', // 移除插入图片
    'uploadVideo', // 移除视频上传
    'codeBlock', // 移除代码块
    'blockquote', // 移除引用
    '|', // 移除分隔符
    'group-more-style', // 移除更多样式组
  ],
  toolbarKeys: [
    'fontFamily',
    'bold',
    'italic',
    'underline',
    'through',
    'color',
    'bgColor',
    'clearStyle',
    'justifyLeft',
    'justifyCenter',
    'justifyRight',
    'justifyJustify',
    'bulletedList',
    'numberedList',
    'fontSize',
    'fontFamily',
    'lineHeight',
    'undo',
    'redo',
  ],
}

const editorConfig = {
  placeholder: '请输入内容...',
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}






//获取日志数据
function fetchData() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  getLog('logsList', data).then((res) => {
    if (res.code === 200) {
      tableData.value = res.dataset.logsList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

//获取个人日志数据
function fetchData1() {
  let data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    userId: user.userId,
  }
  getLogList('logsListPersonal', data).then((res) => {
    if (res.code === 200) {
      tableData.value = res.dataset.logsList
      total.value = res.dataset.pageCount * pageSize.value
    }
  })
}

//获取身份标识列表
function fetchData2() {
  let data = {}
  getLogMenu('roleList', data).then((res) => {
    if (res.code === 200) {
      identityList.value = res.dataset
    }
  })
}


// 处理当前页变化
const handleCurrentPageChange = (value) => {
  currentPage.value = value
  fetchData() // 重新获取数据
}
// 初始化数据
onMounted(() => {
  if (user.roleId == '4') {
    fetchData1()
  } else {
    fetchData()
  }
  fetchData2()
})

// 处理表格行点击事件
const handleRowClick = (row) => {
  selectedRow.value = row
  dialogVisible.value = true
}

// 定义发布日志按钮点击事件
const handleAddLog = () => {
  // 清空编辑器内容
  if (editorRef.value) {
    editorRef.value.clear()
  }
  // 清空表单数据
  formData.value = {
    name: user.userName,
    class: JSON.parse(localStorage.getItem('userClassName')),
    date: '',
    content: '',
    identity: user.roleId,
    sex: user.sex,
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  dialogVisibleLog.value = true
}
// 定义日志模态框显示状态
const dialogVisibleLog = ref(false)
const formRef = ref(null)
const formData = ref({
  name: user.userName,
  class: JSON.parse(localStorage.getItem('userClassName')),
  date: '',
  content: '',
  identity: user.roleId,
  sex: JSON.parse(localStorage.getItem('userSex')),
})
const rules = {
  date: [{ required: true, message: '时间不能为空', trigger: 'blur' }],
  content: [
    {
      validator: (_, __, callback) => {
        if (!valueHtml.value || valueHtml.value.trim() === '<p><br></p>') {
          callback(new Error('请输入报告内容'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

//添加日志接口
function addLog1() {
    let data = {
        userId: user.userId,
        content: editorRef.value.getText(),
        time: formData.value.date,
        className: JSON.parse(localStorage.getItem('userClassName')),
        sex: user.sex,
        userName: user.userName,
        content1:valueHtml.value,
    }
    addLog('addLog', data).then((res) => {
        if (res.code === 200) {
            ElMessage.success('添加成功')
            dialogVisibleLog.value = false
            fetchData1()
        } else {
            ElMessage.error('添加失败')
        }
    })
}

// 处理确认按钮点击事件
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('确认发布日志吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        addLog1()
      }).catch(() => {
        ElMessage.info('已取消发布')
      })
    }
  })
}

function handleChange() {
  currentPage.value = 1 // 重置为第一页
  if (user.roleId == '4') {
    fetchData1()
  } else {
    fetchData()
  }
}
</script>
  
<style scoped>
.class {
  width: 90%;
  height: 10%;
  margin-bottom: 20px;
  margin-top: 20px;
}
/* 头部左侧 */
.header-left {
  display: flex;
  align-items: center;
  margin-left: 40px;
}
.line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
}
.title {
  padding-left: 10px;
  font-size: 20px;
  margin-right: 20px;
}
.className {
  margin-right: 10px;
}

.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 0px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}
.searchImg {
  position: absolute;
  top: 8px;
  left: 25px;
}
/* 头部右侧 */
.header-right {
  display: flex;
  align-items: center;
  margin-right: 40px;
}
.res {
  width: 20px;
  height: 20px;
}
.addRiBao {
  margin-left: 10px;
  font-size: 15px;
}

/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 报告不能换行 */
:deep(.el-table__body-wrapper .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;

}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}

/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-dialog__body){
  display: flex;
  justify-content: center;
}
:deep(.el-select) {
  width: 200px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  color: white;
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}
.richang{
  height: 100%;
}

.name,
.content,
.date {
  color: black;
  font-size: 15px;
  margin-left: 20px;
  margin-bottom: 20px;
}
.content {
  display: flex;
  margin-top: 20px;
  max-height: 70%;
  
}
.content2 {
  width: 570px;
  max-height: 100%;
  overflow-y: auto;
  white-space: pre-line;
  word-break: break-all;
  background-color: white;
  border-radius: 8px;
}
.date {
  margin-top: 20px;
}
.footer {
  padding-top: 20px;
  padding-bottom: 20px;
  text-align: right;
}
.footer button {
  background-color: #0f6ab1;
  color: white;
  margin-right: 20px;
}
.footer button:hover {
  background-color: #054a80;
  color: white;
}
/* 写日报 */


:deep(.el-textarea__inner) {
  min-height: 50px !important;
  max-height: 150px !important;
  overflow-y: auto !important;
}
:deep(.el-drawer header) {
  background-color: #0f6ab1;
  margin-bottom: 0;
  padding-bottom: 20px;
}
:deep(.el-drawer header span) {
  color: white;
}

:deep(.el-drawer__header span){
  text-align: center;
  color: black;
  font-size: 20px;
}
:deep(.w-e-scroll p) {
  margin: 0;
}
.content1{
  min-width: 51px;
}
</style>